package lt.marsrutai.mobile.android.util;

import java.util.Collection;
import java.util.Iterator;

/**
 * Utility class for common string operations
 * 
 * @author Justas
 *
 */
public class StringUtils {
    
    public static String EMPTY = "";
    
    /**
     * Compares two strings.
     * 
     * @param str1
     * @param str2
     * @return
     */
    public static boolean equals(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equals(str2);
    }
    
    /**
     * Checks if the provided string is empty
     * <pre>
     * isEmpty("a")   - false
     * isEmpty(" ")   - false
     * isEmpty("")    - true
     * isEmpty(null)  - true
     * </pre>
     * 
     * @param string
     * @return
     */
    public static boolean isEmpty(String string) {
        return EMPTY.equals(string);
    }
    
    /**
     * Capitalizes the given string
     * 
     * @param string
     * @return
     */
    public static String capitalize(String string) {
        String result = EMPTY;
        
        for (int i = 0; i < string.length(); i++) {
            result += Character.toUpperCase(string.charAt(i));
        }
        
        return result;
    }

    public static String join(Collection<?> collection, String separator) {
        Iterator<?> iterator = collection.iterator();
        
        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }

        if (!iterator.hasNext()) {
            return EMPTY;
        }

        Object first = iterator.next();
        if (!iterator.hasNext()) {
            return first.toString();
        }

        // two or more elements
        String result = EMPTY;

        if (first != null) {
            result += first;
        }

        while (iterator.hasNext()) {
            result += separator;
            
            Object obj = iterator.next();
            if (obj != null) {
                result += obj;
            }
        }
        
        return result;
    }
}
